package web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import vo.Log;
import vo.SourceCategory;
import vo.Topic;
import vo.User;
import vo.UserGroup;
import vo.UserTopic;
import business.LogService;
import business.UserGroupService;
import business.UserService;
import business.UserTopicService;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@SuppressWarnings("unchecked")
public class UserAction extends ActionSupport implements Preparable {
	private UserService service;
	private LogService logService;
	private UserGroupService userGroupService;
	private UserTopicService userTopicService;

	private User curUser;
	private List<User> users;
	private List<UserGroup> userGroups;
	private ArrayList<String> delIds = new ArrayList<String>();

	// 分页的变量
	private int curPage;
	private int totalPage;
	private int pageSize = 5;

	private String newPSW;

	/** 新增用户参数 */
	private String username;
	private String password;
	private String mobile;
	private String phone;
	private String email;
	private String department;
	private String name;
	private int userGroup;
	private String loginName;

	private String errorMsg;
	// 更新用户
	private int userId;
	private int userGroupId;

	public String logout() {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		session.clear();
		System.out.println("clear session");
		Log log = new Log();
		log.setDttm(new Date());
		log.setMessage("退出");
		log.setUser(curUser);
		log.setType("LOGOUT");
		logService.addLog(log);
		return Action.SUCCESS;

	}

	public String login() {
		
		System.out.println("login:" + username + "," + password);
		User user = service.getByUsernamePSW(username, password);
		System.out.println("role:" + user.getUserGroup().getRole());

		// login succ
		if (user != null) {
			ActionContext ctx = ActionContext.getContext();
			Map session = ctx.getSession();
			session.clear();//初始化之前，清除所有的session
			session.put("username", username);
			session.put("role", user.getUserGroup().getRole());

			//更新最后登录时间
			user.setLastLogin(new Date());
			service.update(user);

			// admin login
			Log log = new Log();
			log.setDttm(new Date());
			log.setMessage("登录");
			log.setUser(curUser);
			log.setType("LOGIN");
			logService.addLog(log);

			if (user.getUserGroup().getRole().equals("admin")) {
				return "loginAdmin";
			}
			// member login
			else if (user.getUserGroup().getRole().equals("user")) {
				return "loginUser";
			} else
				return "loginError";
		} else
			return "loginError";
	}

	public String listUser() {
		System.out.println("curPage:" + curPage);
		int totalCount = (int) service.getTotalCount();
		System.out.println("totalCount:" + totalCount);
		if (totalCount % pageSize == 0)
			totalPage = totalCount / pageSize;
		else
			totalPage = totalCount / pageSize + 1;
		System.out.println("totalCount / pageSize:" + totalCount / pageSize);

		if (curPage == 0)
			curPage = 1;
		this.users = service.getAllUsers((curPage - 1) * pageSize, pageSize);
		System.out.println("user count:" + this.users.size());
		return Action.SUCCESS;
	}

	public String addUser() {
		service.addUser("hello xxx");
		return listUser();
	}

	public String deleteUser() {
		System.out.println("delete user:");
		for (int i = 0; i < this.delIds.size(); i++) {
			System.out.println("deleted ids：" + delIds.get(i));
			long userId = Long.parseLong(delIds.get(i));

			// 如果和topic关联
			List<UserTopic> uts = userTopicService.getUserTopicsByUserId(userId);
			if (uts != null && uts.size() > 0) {
				this.errorMsg = "Can't Delete!";
				return "userDeleteError";
			}
			// 删除级联的log
			List<Log> logs = logService.getByUserId(userId);
			for (Log l : logs) {
				logService.delete(l.getId());
			}

			service.delete(userId);
		}
		return "userDeleted";
	}

	public String saveUser() {
		System.out.println("form save user:" + username + "," + mobile + "," + email + "," + name + "," + department + "," + userGroup);
		User user = new User();
		user.setLoginName(username);
		user.setPassword(password);
		user.setDepartment("");// TODO:部门暂时没什么用
		user.setEmail(email);
		user.setMobile(mobile);
		user.setPhone(phone);
		user.setName(name);
		user.setUserGroup(userGroupService.getById(userGroup));

		service.addUser(user);
		return "saveUser";
	}

	public String profile() {
		System.out.println("profile");
		return Action.SUCCESS;
	}

	public String changePSW() {
		System.out.println("changePSW");
		return Action.SUCCESS;
	}

	public String savePSW() {
		System.out.println("savePSW");
		curUser.setPassword(newPSW);
		service.update(curUser);
		return "savePSW";
	}

	public String changeProfile() {
		System.out.println("change profile");
		return Action.SUCCESS;
	}

	public String updateUser() {
		System.out.println("form update user:");
		System.out.println("name:" + curUser.getName());
		System.out.println("loginName:" + curUser.getLoginName());
		System.out.println("email:" + curUser.getEmail());
		System.out.println("mobile:" + curUser.getMobile());
		System.out.println("phone:" + curUser.getPhone());
		System.out.println("department:" + curUser.getDepartment());
		service.update(curUser);
		return "updateUser";
	}

	// 显示编辑的页面
	public String editUser() {
		System.out.println("edit user:" + userId);
		User user = service.getById(userId);

		this.loginName = user.getLoginName();
		this.mobile = user.getMobile();
		this.email = user.getEmail();
		this.name = user.getName();
		this.userGroupId = user.getUserGroup().getId().intValue();
		System.out.println("userGroupId:" + userGroupId);
		userGroups = userGroupService.getAllUserGroups();

		return Action.SUCCESS;
	}

	public String updateUserAdmin() {
		System.out.println("update user by admin");
		System.out.println(userId + "," + loginName + "," + email + "," + mobile + "," + name + "," + userGroupId);
		User user = service.getById(userId);
		user.setLoginName(loginName);
		user.setMobile(mobile);
		user.setEmail(email);
		user.setName(loginName);
		UserGroup userGroup = userGroupService.getById(userGroupId);
		user.setUserGroup(userGroup);
		service.update(user);
		return "updateUserAdmin";
	}

	public List<User> getUsers() {
		return users;
	}

	public void prepare() throws Exception {
		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		String username = (String) session.get("username");
		curUser = service.getByLoginName(username);
		this.userGroups = userGroupService.getAllUserGroups();
	}

	public void setUserService(UserService service) {
		this.service = service;
	}

	public void setService(UserService service) {
		this.service = service;
	}

	public ArrayList<String> getDelIds() {
		return delIds;
	}

	public void setDelIds(ArrayList<String> delIds) {
		this.delIds = delIds;
	}

	public void setUsers(List<User> users) {
		this.users = users;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setUserTopicService(UserTopicService userTopicService) {
		this.userTopicService = userTopicService;
	}

	public void setLogService(LogService logService) {
		this.logService = logService;
	}

	public void setUserGroupService(UserGroupService userGroupService) {
		this.userGroupService = userGroupService;
	}

	public User getCurUser() {
		return curUser;
	}

	public void setCurUser(User curUser) {
		this.curUser = curUser;
	}

	public int getCurPage() {
		return curPage;
	}

	public void setCurPage(int curPage) {
		this.curPage = curPage;
	}

	public int getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getNewPSW() {
		return newPSW;
	}

	public void setNewPSW(String newPSW) {
		this.newPSW = newPSW;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public List<UserGroup> getUserGroups() {
		return userGroups;
	}

	public void setUserGroups(List<UserGroup> userGroups) {
		this.userGroups = userGroups;
	}

	public int getUserGroup() {
		return userGroup;
	}

	public void setUserGroup(int userGroup) {
		this.userGroup = userGroup;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public int getUserGroupId() {
		return userGroupId;
	}

	public void setUserGroupId(int userGroupId) {
		this.userGroupId = userGroupId;
	}

}